package aiP.A3.MPS;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.Socket;

class ServerEKG extends Thread {
    private final ServerInstance serverInstance;

    public ServerEKG(ServerInstance serverInstance) {
        this.serverInstance = serverInstance;
    }

    public void run() {
        try {
            while (this.serverInstance.running) {
                sendLifeSign(this.serverInstance.serverId);
                Thread.sleep(200);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendLifeSign(String serverId) throws IOException {
        try{
            Socket socket = new Socket(this.serverInstance.monitorHost, this.serverInstance.monitorPort);
            socket.setReuseAddress(true);
            OutputStream out = socket.getOutputStream();
            out.write(serverId.getBytes());
            out.close();
            socket.close();
        }catch(ConnectException c){
            c.printStackTrace();
        }

    }
}